package com.xinchao.controller;

import com.xinchao.constant.BusinessConstant;
import com.xinchao.constant.RequestConstant;
import com.xinchao.constant.ResponseConstant;
import com.xinchao.exception.ControllerException;
import com.xinchao.model.Department;
import com.xinchao.model.User;
import com.xinchao.model.page.PageInfo;
import com.xinchao.model.sys.JsonResponse;
import com.xinchao.model.vo.DepartmentListVO;
import com.xinchao.service.DepartmentService;
import com.xinchao.util.HttpUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping(value = "/department")
public class DeparmentController {
	private static Logger logger = LoggerFactory.getLogger(DeparmentController.class);

	@Autowired
	private DepartmentService departmentService;

	/**
	 * 保存部门
	 * @param department Department 部门实体
	 * @param cityCodes    城市编码
	 * @param cityNames    城市名称
	 */
	@ResponseBody
	@RequestMapping("/save")
	public Object saveDepartment(Department department, String cityCodes, String cityNames, HttpServletRequest request) {
		//检验部门名称是否为空
		if (StringUtils.isBlank(department.getDepartmentName())) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "部门名称不能为空");
		}
		//检验部门编码是否为空
		if (StringUtils.isBlank(department.getDepartmentCode())) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "部门编码不能为空");
		}
		try {
			departmentService.insertDepartment(department, cityCodes, cityNames, request);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("DeparmentController saveDepartment 保存部门失败：" + e.getMessage());
			return new ControllerException("保存部门失败");
		}
		return "";
	}

	/**
	 * 修改部门
	 * @param department Department 部门实体
	 * @param cityCodes    城市编码
	 * @param cityNames    城市名称
	 */
	@ResponseBody
	@RequestMapping("/update")
	public Object updateDepartment(Department department, String cityCodes, String cityNames, HttpServletRequest request) {
		//检验部门名称是否为空
		if (StringUtils.isBlank(department.getDepartmentName())) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "部门名称不能为空");
		}
		//检验部门编码是否为空
		if (StringUtils.isBlank(department.getDepartmentCode())) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "部门编码不能为空");
		}
		try {
			departmentService.updateDepartment(department, cityCodes, cityNames, request);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("DeparmentController updateDepartment 修改部门失败：" + e.getMessage());
			return new ControllerException("修改部门失败");
		}
		return "";
	}

	/**
	 * 部门列表
	 */
	@RequestMapping(value = "/list")
	public String listDepartment(Integer status, String departmentName, Integer pageNum, Integer pageSize, Model model, HttpServletRequest request) {
		try {
			PageInfo<DepartmentListVO> pageInfo = departmentService.listDepartment(status, departmentName, pageNum, pageSize);
			model.addAttribute("status", status);
			model.addAttribute("departmentName", departmentName);
			model.addAttribute("departmentList", pageInfo.getList());
			model.addAttribute("pageNum", pageInfo.getPageNum());
			model.addAttribute("pageSize", pageInfo.getPageSize());
			model.addAttribute("total", pageInfo.getTotal());
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("DeparmentController listDepartment 获取部门列表失败：" + e.getMessage());
		}
		return "department_list";
	}

	/**
	 * 部门选择列表
	 */
	@ResponseBody
	@RequestMapping("/listDepartmentSelect")
	public Object listDepartmentSelect() {
		try {
			return departmentService.listDepartmentSelect();
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("DeparmentController listDepartmentSelect 获取角色选择列表失败：" + e.getMessage());
			return new ControllerException("获取角色选择列表失败： " + e.getMessage());
		}
	}


	/**
	 * 启用禁用部门
	 */
	@ResponseBody
	@RequestMapping(value = "/enableDisableDepartment", method = RequestMethod.POST)
	public Object enableDisableDepartment(Long departmentId, Integer status, HttpServletRequest request) {
		if (departmentId == null) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "部门ID不能为空，请联系管理员");
		}
		if (status == null) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "状态数据不能为空，请联系管理员");
		}
		try {
			departmentService.enableDisableDepartment(departmentId, status, request);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("DeparmentController enableDisableDepartment 启用禁用部门失败：" + e.getMessage());
			return new ControllerException("启用禁用部门失败： " + e.getMessage());
		}
		return "";
	}

	/**
	 * 批量启用部门
	 *
	 * @param ids        部门id(多个英文逗号隔开)
	 * @param status     状态（0启用，1禁用）
	 * @param request    请求
	 * @author linqiang
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/batchAbleDisable", method = RequestMethod.POST)
	public Object batchAbleDisable(String ids,Integer status, HttpServletRequest request) {
		if (StringUtils.isBlank(ids)) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "请选择需要启用的部门");
		}
		if (status == null) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "状态不能为空，请联系管理员");
		}
		try {
			User loginUser = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
			String ip = HttpUtils.getRemortIP(request);
			departmentService.batchAbleDisable(ids, status, loginUser, ip);
			if(BusinessConstant.STATUS_ENABLE == status){
				return new JsonResponse(ResponseConstant.CODE_SUCCESS, "批量启用部门成功");
			} else {
				return new JsonResponse(ResponseConstant.CODE_SUCCESS, "批量禁用部门成功");
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("DeparmentController batchAbleDisable 批量启用禁用部门失败：" + e.getMessage());
		}
		if(BusinessConstant.STATUS_ENABLE == status){
			return new JsonResponse(ResponseConstant.CODE_FAIL, "批量启用部门失败");
		} else {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "批量禁用部门失败");
		}
	}

	/**
	 * 跳转至选择部门页面
	 */
	@RequestMapping(value = "/goDepartmentPickerPage")
	public String goDepartmentPickerPage() {
		return "department_picker";
	}

	/**
	 * 获取部门树列表
	 */
	@ResponseBody
	@RequestMapping(value = "/listDepartmentTree", method = RequestMethod.POST)
	public Object listDepartmentTree() {
		try {
			return departmentService.listDepartmentTree();
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("DeparmentController listDepartmentTree 获取部门树列表失败：" + e.getMessage());
			return e;
		}
	}

	/**
	 * 跳转至选择城市页面
	 */
	@RequestMapping(value = "/goSelectCity")
	public String goSelectCity() {
		return "select_city";
	}

}
